<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>函数防抖</title>
    <style>
      .container {
        margin: 100px auto 0;
        width: 200px;
        height: 200px;
        border: 1px solid#000000;
        /* 针对所有溢出属性不可见的元素 */
        /* inline elements、overflow： visible 不生效 */
        resize: both;
        overflow: hidden;
      }
    </style>
  </head>
  <body>
    <div class="container">内容区域</div>
    <script>
      const container = document.querySelector(".container");
      /**
       * @param {*} fn
       * @param {*} duration
       * @return {*}
       * @Author: Hisun 958306134@qq.com
       * @LastEditors: Hisun 958306134@qq.com
       * @Date: 2024-07-24 22:39:15
       * @Description: 使用场景: 1.频繁操作; 2.耗时操作; 3.仅关心最后一次的触发
       */
      function debounce(fn, duration = 250) {
        let timerId; // 记录上一次的计时器id
        return function (...args) {
          console.log("........");
          timerId && clearTimeout(timerId);
          timerId = setTimeout(() => {
            fn && fn.apply(this, args); // 耗时操作
          }, duration);
        };
      }
      function resizeDom() {
        console.log("非耗时操作");
      }
      function updateData() {
        return new Promise((resolve) => {
          const timer = setTimeout(() => {
            clearTimeout(timer);
            console.log("耗时操作....获取数据了");
            resolve(true);
          }, 500);
        });
      }
      const newUpdateData = debounce(updateData);
      const handler = () => {
        // 非耗时逻辑
        resizeDom();
        // 耗时逻辑 - 只针对耗时逻辑防抖
        newUpdateData();
      };
      container.addEventListener("resize", handler);
    </script>
  </body>
</html>
